using GraphQLDemo.Api.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddGraphQLService();
builder.Services.AddQueryService();
builder.Services.AddRepositoryService();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("Global", x => x.RequireClaim("Role1"));
});

var app = builder.Build();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseGraphQL("/graphql");
app.UseGraphQLGraphiQL("/ui/graphiql");
app.UseGraphQLVoyager("/ui/voyager");
app.Map("/cookie", builder => builder.Run(async context =>
{
    var claims = new List<Claim>()
    {
        new Claim("id","1")
    };
    var roleList = new List<string>()
    {
        "Admin"
    };
    foreach (var role in roleList)
    {
        claims.Add(new Claim(ClaimTypes.Role, role));
    }

    var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
    await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal, new AuthenticationProperties
    {
        ExpiresUtc = DateTime.Now.AddMinutes(30)
    });
    await context.Response.WriteAsync(context.Response.Headers.SetCookie);
}));
app.Run();